import { Directive, ElementRef } from '@angular/core';
import { FormControl, NgControl } from "@angular/forms";

/**
 * 为了解决Angular自带的必填校验空格有效的问题，创建此Directive
 */
@Directive({
  selector: '[required]'
})
export class RequiredDirective {

  constructor(private elementRef: ElementRef, private control: NgControl) {
    if (control && control.control) {
      control.control.setValidators((c: FormControl) => {
        let v = c.value === 0 ? '0' : c.value;
        if (!v || v.toString().trim() == '') {
          return { 'required': true };
        }
        return null;
      });
    }
  }

}
